package io.dcloud.uniplugin;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;


public class TestModule extends UniModule {

    String TAG = "TestModule";
    public static int REQUEST_CODE = 1000;

    //run ui thread
    @UniJSMethod(uiThread = true)
    public void testAsyncFunc(JSONObject options, UniJSCallback callback) {
        Log.e(TAG, "testAsyncFunc执行: " + options);
        if (callback != null) {
            JSONObject data = new JSONObject();
            data.put("code", "success");
            callback.invoke(data);
            //callback.invokeAndKeepAlive(data);
        }
    }

    @UniJSMethod(uiThread = true)
    public void slientInstall(JSONObject options, UniJSCallback callback) {
        Log.e(TAG, "slientInstall执行: " + options);
        if (callback != null) {
            String filePath = options.getString("filePath");
            if (filePath != null) {
                int result = -1;
                Process process = null;
                BufferedReader successResult = null;
                BufferedReader errorResult = null;
                StringBuilder stdout = null;
                StringBuilder stderr = null;
                DataOutputStream os = null;

                JSONObject map = new JSONObject();

                try {
                    process = Runtime.getRuntime().exec("su");
                    os = new DataOutputStream(process.getOutputStream());

                    os.write(new StringBuffer().append("chmod 777 ").append(filePath).toString().getBytes());
                    os.writeBytes("\n");
                    os.write(new StringBuffer().append("LD_LIBRARY_PATH=/vendor/lib*:/system/lib* ").append("pm install -r ").append(filePath).toString().getBytes());
                    os.writeBytes("\n");
                    os.flush();

                    os.writeBytes("exit\n");
                    os.flush();
                    result = process.waitFor();
                    stdout = new StringBuilder();
                    stderr = new StringBuilder();
                    successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));

                    String s;
                    while ((s = successResult.readLine()) != null) {
                        stdout.append(s);
                    }

                    while ((s = errorResult.readLine()) != null) {
                        stderr.append(s);
                    }
                } catch (IOException e) {
                    Log.e(TAG, "发生了错误: " + e.getMessage());
                } catch (Exception e) {
                    Log.e(TAG, "发生了错误: " + e.getMessage());
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }

                        if (successResult != null) {
                            successResult.close();
                        }

                        if (errorResult != null) {
                            errorResult.close();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "发生了错误: " + e.getMessage());
                    }

                    if (process != null) {
                        process.destroy();
                    }

                    map.put("stdout", String.valueOf(stdout));
                    map.put("stderr", String.valueOf(stderr));
                    map.put("exitValue", result);
                }

                callback.invoke(map);
            } else {
                callback.invoke(new JSONObject() {{
                    put("stdout", "");
                    put("stderr", "没有获取到 filePath 字段参数, 请检查");
                    put("exitValue", 1);
                }});
            }
        }
    }

    @UniJSMethod(uiThread = true)
    public void cmd(JSONObject options, UniJSCallback callback) {
        Log.e(TAG, "cmd执行: " + options);
        if (callback != null) {
            String cmd = options.getString("cmd");
            if (cmd != null) {
                Log.e(TAG, "运行命令: " + cmd);
                JSONObject result = execShell(cmd, true);
                callback.invoke(result);
            } else {
                callback.invoke(new JSONObject() {{
                    put("stdout", "");
                    put("stderr", "没有获取到 cmd 字段参数, 请检查");
                    put("exitValue", 1);
                }});
            }
        }
    }

    //run JS thread
    @UniJSMethod(uiThread = false)
    public JSONObject testSyncFunc() {
        JSONObject data = new JSONObject();
        data.put("code", "success");
        return data;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && data.hasExtra("respond")) {
            Log.e("TestModule", "原生页面返回----" + data.getStringExtra("respond"));
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @UniJSMethod(uiThread = true)
    public void gotoNativePage() {
        if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
            Intent intent = new Intent(mUniSDKInstance.getContext(), NativePageActivity.class);
            ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
        }
    }

    /////

    /**
     * 执行 shell 命令
     *
     * @param cmd    命令字符串
     * @param isRoot 是否 Root
     * @return
     */
    public JSONObject execShell(final String cmd, boolean isRoot) {
        int result = -1;
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder stdout = null;
        StringBuilder stderr = null;
        DataOutputStream os = null;

        JSONObject map = new JSONObject();

        try {
            process = Runtime.getRuntime().exec(isRoot ? "su" : "sh");
            os = new DataOutputStream(process.getOutputStream());

            os.write(cmd.getBytes());
            os.writeBytes("\n");
            os.flush();

            os.writeBytes("exit\n");
            os.flush();
            result = process.waitFor();
            stdout = new StringBuilder();
            stderr = new StringBuilder();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            String s;
            while ((s = successResult.readLine()) != null) {
                stdout.append(s);
            }

            while ((s = errorResult.readLine()) != null) {
                stderr.append(s);
            }
        } catch (IOException e) {
            Log.e(TAG, "发生了错误: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "发生了错误: " + e.getMessage());
        } finally {
            try {
                if (os != null) {
                    os.close();
                }

                if (successResult != null) {
                    successResult.close();
                }

                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "发生了错误: " + e.getMessage());
            }

            if (process != null) {
                process.destroy();
            }

            map.put("stdout", String.valueOf(stdout));
            map.put("stderr", String.valueOf(stderr));
            map.put("exitValue", result);

            return map;
        }
    }
}
